<template>
    <div class="app-container x-container" v-loading="loading">
        <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="100px" class="demo-ruleForm">
            <el-form-item label="攻略标题" prop="title">
                <el-input v-model="ruleForm.title" placeholder="请输入攻略标题" maxlength="50" clearable />
            </el-form-item>
            <el-row>
                <el-col :span="12">
                    <el-form-item label="关键字" prop="keywords_id">
                        <el-select filterable :filter-method="filterFun" v-model="ruleForm.keywords_id"
                            placeholder="请选择关键字" clearable>
                            <el-option :label="ietm.name" :value="ietm.id" v-for="(ietm, value) in filteredOptions" />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="12">
                    <el-form-item label="所属分类" prop="category_id">
                        <el-select v-model="ruleForm.category_id" placeholder="请选择所属分类" clearable>
                            <el-option :label="key" :value="value" v-for="(key, value) in publicParams.ARTICLE_TYPE" />
                        </el-select>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-form-item label="SEO标题" prop="page_title">
                <el-input v-model="ruleForm.page_title" placeholder="请输入SEO标题" maxlength="500" clearable />
            </el-form-item>
            <el-form-item label="SEO关键词" prop="page_keywords">
                <el-input v-model="ruleForm.page_keywords" placeholder="请输入SEO关键词" maxlength="50" clearable />
            </el-form-item>
            <el-form-item label="SEO描述" prop="page_description">
                <el-input type="textarea" v-model="ruleForm.page_description" placeholder="请输入SEO描述" maxlength="500"
                    autosize clearable />
            </el-form-item>
            <el-form-item label="游戏介绍" prop="content">
                <vue-ueditor-wrap v-model="ruleForm.content" editor-id="editor" />
            </el-form-item>
            <el-form-item label="文章首页图(380*214)" prop="cover">
                <FileUpload v-model="ruleForm.cover" :limit="1"></FileUpload>
            </el-form-item>
            <el-form-item label="下载详情页图(308*351)" prop="image">
                <FileUpload v-model="ruleForm.image" :limit="1"></FileUpload>
            </el-form-item>
            <div class="flex">
                <el-form-item label="发布时间" prop="release_time">
                    <el-date-picker format="YYYY-MM-DD HH:mm:ss" value-format="YYYY-MM-DD HH:mm:ss" time-format="HH:mm"
                        :disabled-date="disabledBeforeToday" v-model="ruleForm.release_time" type="datetime"
                        placeholder="请选择" />
                </el-form-item>
                <el-form-item prop="is_recommend">
                    <el-checkbox :true-value="1" :false-value="0" v-model="ruleForm.is_recommend"
                        name="type">首页推荐</el-checkbox>
                </el-form-item>
                <el-form-item prop="is_timing">
                    <el-checkbox :true-value="1" :false-value="0" @change="timingChange" v-model="ruleForm.is_timing"
                        name="type">定时发布</el-checkbox>
                </el-form-item>
            </div>

            <el-row>
                <el-col class="flex-center-align" :span="24">
                    <el-button @click="cancelForm(ruleFormRef)">取消</el-button>
                    <el-button @click="resetForm(ruleFormRef)">重置</el-button>
                    <el-button type="primary" @click="submitForm(ruleFormRef)">提交</el-button>
                    <el-button type="primary" @click="submitForm(ruleFormRef, 1)">提交并发布</el-button>
                </el-col>
            </el-row>
        </el-form>
    </div>

</template>

<script setup>
import { addArticle, editArticle, getArticleDetail } from '@/api/article'
import { allKeyword } from '@/api/keywords'
import { subSelect } from '@/api/tag'
import { reactive, ref, toRaw, inject } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import VueUeditorWrap from '@/components/VueUeditorWrap.vue'

const router = useRouter();
const route = useRoute();
const publicParams = inject('publicParams')
const used = inject('used');


const ruleFormRef = ref()
const ruleForm = reactive(
    {
        title: '',//文章标题
        category_id: '',//关键词ID
        keywords_id: '',//分类ID 1=游戏攻略 2=软件教程 3=活动杂谈
        page_title: '',//页面title
        page_keywords: '',//页面keywords
        page_description: '',//页面description
        content: '',//文章内容
        cover: '',//缩略图
        image: '',//下载详情页图
        release_time: '',//发布时间 
        is_recommend: '0',//是否推荐 0=否 1=是
        is_timing: '0',//是否定时发布 0=否 1=是
    }
)

const rules = reactive(
    {
        title: [
            { required: true, message: '请输入攻略标题', trigger: 'blur' },
        ],
        category_id: [
            { required: true, message: '请选择所属分类', trigger: 'change' },
        ],
        keywords_id: [
            { required: true, message: '请选择关键字', trigger: 'change' },
        ],
        page_title: [
            { required: true, message: '请输入SEO标题', trigger: 'blur' },
        ],
        page_keywords: [
            { required: true, message: '请输入SEO关键字', trigger: 'blur' },
        ],
        page_description: [
            { required: true, message: '请输入SEO描述', trigger: 'blur' },
        ],
        image: [
            { required: true, message: '请上传文章首页图', trigger: 'change' },
        ],
        release_time: [
            { required: false, message: '请选择发布时间', trigger: 'change', },
        ],
    }
)

//选择是否确认定时发布
const timingChange = (type) => {
    if (type == '1') {
        rules.release_time = [
            { required: true, message: '请选择发布时间', trigger: 'change', },
        ]
    } else {
        rules.release_time = [
            { required: false, message: '请选择发布时间', trigger: 'change', },
        ]
    }
}
//时间选择器禁止选择今天之前的日期
const disabledBeforeToday = (date) => {
    const today = new Date();
    today.setHours(0, 0, 0, 0); // 确保比较的是当天的开始时间
    return date < today;
};
/* 获取详情数据 */
let loading = ref(false);
const getDetail = async () => {
    const { data } = await getArticleDetail({ id: route.query.id }, 'get')
    data.category_id = data.category_id + ''
    Object.assign(ruleForm, data)
    timingChange(ruleForm.is_timing)
    getallKeyword();
    loading.value = false;
}
let id = route.query.id;
if (id) {
    loading.value = true;
    getDetail()
} else {
    getallKeyword()
}

//提交
const submitForm = async (formEl, type) => {
    if (!formEl) return
    await formEl.validate(async (valid, fields) => {
        if (valid) {
            let params = { ...ruleForm };
            type == 1 ? params.status = 1 : '';
            let res = id ? await editArticle(params, 'post') : await addArticle(params);
            if (res.code == 1) {
                used.msgSuccess(res.message)
                router.go(-1)
            } else {
                used.msgError(res.message)
            }
        } else {
            console.log('error submit!', fields)
        }
    })
}
//取消
const cancelForm = (formEl) => {
    console.log('cancel!')
    router.go(-1)
}
//重置
const resetForm = (formEl) => {
    if (!formEl) return
    formEl.resetFields()
}

//获取关键词列表
let gjcListAll = ref([]);//全部
let gjcListSt = ref([]);//前50条
let filteredOptions = ref([]);//实际选择的数组

function getallKeyword() {
    let kId = ruleForm.keywords_id;
    allKeyword().then(res => {
        let list = res.data;
        gjcListAll.value = list;
        gjcListSt.value = list.slice(0, 50);
        filteredOptions.value = [...gjcListSt.value];
        //查看当前选择列表中是否包含当前选择 没有去全部中查询 并添加到选择列表中

        if (!gjcListSt.value.some(item => item.id == kId)) {
            let item = gjcListAll.value.find(item => item.id == kId);
            if (item) {
                gjcListSt.value.push(item);
                filteredOptions.value.push(item);
            }
        }
    })
}


// 多选过滤方法
const filterFun = (query) => {
    if (query === '') {
        filteredOptions.value = [...gjcListSt.value];
    } else {
        filteredOptions.value = gjcListAll.value.filter(item =>
            item.name.includes(query)
        )
    }
}
</script>

<style scoped lang="scss">
.x-container {
    position: relative;
    padding: 20px;
    background-color: #fff;
}
</style>